package com.hello.Launcher;


import com.hello.MainMenuScreen;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;

public class LocationLauncherService extends Service {
	
	private boolean isActive;
	LocationListener locationListener;
	LocationManager locationManager;
	Location location;
	String provider;
	static boolean isServiceOn = false;
	boolean isAlreadyAsked = false;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		locationListener = new LocationListener() {
	        public void onLocationChanged(Location m_location) {
	        	//Toast.makeText(LocationLauncherService.this, "OnLocationChanged", Toast.LENGTH_LONG).show();
	            location = m_location;
	        }

			public void onProviderDisabled(String provider) {
	            
	        }

	        public void onProviderEnabled(String provider) {
	        }

	        public void onStatusChanged(String provider, int status, Bundle extras) {
	        }
	    };
	    
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		isActive = true;
	}

	@Override
	public void onDestroy() {
		locationManager.removeUpdates(locationListener);
		super.onDestroy();		
	}

	@Override
	public int  onStartCommand(Intent intent,int flags, int startId) {
		super.onStart(intent, startId);
		if (isServiceOn == false){
			isAlreadyAsked = false;
			isServiceOn = true;
			setFromPref();
			if (isActive){
				//Toast.makeText(LocationLauncherService.this, "OnStartCmd", Toast.LENGTH_LONG).show();
				Criteria criteria = new Criteria();
		        criteria.setAccuracy(Criteria.ACCURACY_FINE);
		        criteria.setAltitudeRequired(false);
		        criteria.setBearingRequired(false);
		        criteria.setCostAllowed(true);
		        criteria.setPowerRequirement(Criteria.POWER_LOW);
		        //provider = locationManager.getBestProvider(criteria, true);
		        provider = LocationManager.NETWORK_PROVIDER;
		        recursivlyFindLocation();
		        Handler handler = new Handler();
				handler.postDelayed(new Runnable() {			
					public void run() {
						isServiceOn = false;
						stopSelf();
					} 
				},6* 60  * 60 * 1000);//6 hours
			}
		}
		return START_STICKY;
	}
	
	private void recursivlyFindLocation() {
		//Toast.makeText(LocationLauncherService.this, "RecursivlyFindLocation", Toast.LENGTH_LONG).show();
		 Handler handler = new Handler();
		 handler.postDelayed(new Runnable() {			
				public void run() {
					location = locationManager.getLastKnownLocation(provider);
					locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {			
						public void run() {
							try{
								if (location != null){
									 sendLocationToServer(location);
								 }
							}
							catch (Exception e) {
								
							}
							locationManager.removeUpdates(locationListener);
							if (isServiceOn){
								recursivlyFindLocation();
							}
						} 
					},10 * 1000);
				} 
			}, 10 * 60 * 1000);
		
	}

	private void setFromPref() {
		SharedPreferences pref = getSharedPreferences("com.hello_preferences", MODE_WORLD_READABLE);
		isActive = pref.getBoolean("locationEnabled", true);		
	}

	public void sendLocationToServer(Location location) {
		//Toast.makeText(LocationLauncherService.this, "OnSendLocation", Toast.LENGTH_LONG).show();
		TelephonyManager manager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		String id = manager.getDeviceId();
		try{
			if (MainMenuScreen.IsDrunk){
				//Toast.makeText(LocationLauncherService.this, "Sending Location", Toast.LENGTH_LONG).show();
				CommunicationMgr.sendLocation(id, location.getLongitude(), location.getLatitude());
			}
			else{
				if (!isAlreadyAsked){
				//Toast.makeText(LocationLauncherService.this, "Isnear", Toast.LENGTH_LONG).show();
				int isNear = CommunicationMgr.isNearCluster(id, location.getLongitude(), location.getLatitude());
				if (isNear > 0){ //if nearby user is drunk
					//Toast.makeText(LocationLauncherService.this, "Isnear = true", Toast.LENGTH_LONG).show();
					Intent intent = new Intent(LocationLauncherService.this,LaunchAppFromGame.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					LocationLauncherService.this.startActivity(intent);
					isAlreadyAsked = true;						
					}
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
